﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace PhilWicklund.com.SiteCreationWorkflow.Utilities
{
	public static class WorkflowUtil
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="web">Current context web</param>
		/// <returns>
		/// returns a string that contains the URL where the user should be redirected
		/// after the workflow has been consulted
		/// </returns>
		public static string StartWorkflow(string webUrl)
		{
			string redirectURL = "";
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite site = new SPSite(webUrl))
				{
					string relativeWebUrl = "";
					if (site.Url != webUrl) // NOT Root Web
						relativeWebUrl = webUrl.Substring(site.Url.Length + 1);
					using (SPWeb web = site.OpenWeb(relativeWebUrl))
					{
						// If Web was created more than 1 day ago,
						// it is an old web, mark as approved
						if (web.IsRootWeb || web.Created.Date < DateTime.Today)
						{
							WorkFlowStatusService.SetWorkflowStatus(
								web.Url,
								ApprovalWorkflowStatus.Approved
								);
						}
						// Start Workflow
						else
						{
							// Create a new list item to start the .NET workflow for approval
							WorkflowItemFactory.CreateNewItem(web);

							// Set status from "Null" to be "New"
							WorkFlowStatusService.SetWorkflowStatus(web.Url, ApprovalWorkflowStatus.New);

							// Redirect to form where user can input their justification for new site
							redirectURL = "_layouts/happenings/sitecreationworkflow/newsbwebworkflow.aspx";
						}
					}
				}
			});
			return redirectURL;
		}

		public static bool WorkflowIsComplete(SPWeb web)
		{
			ApprovalWorkflowStatus status = WorkFlowStatusService.GetWorkflowStatus(web.Url);
			if (web.IsRootWeb || 
				status != ApprovalWorkflowStatus.New &&
				status != ApprovalWorkflowStatus.Null)
				return true;
			
			return false;
		}

		public static bool ShouldStartWorkflow(SPWeb web)
		{
			ApprovalWorkflowStatus status = WorkFlowStatusService.GetWorkflowStatus(web.Url);
			if (status == ApprovalWorkflowStatus.Null)
				return true;

			return false;		
		}
	}
}
